# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import cgi
import sys
import os
from google.appengine.api import users
from google.appengine.ext import webapp,db
import logging
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp import template

from django.utils import simplejson

from osapps.common.request import *
from osapps.gtest.model import *
from osapps.gtest import tools
from osapps.gtest import commands
config = {"default":{"init_cash":10000,"init_price":500,
            "fix_interval":12,"reward_interval":12,
            "fawn_interval":12,"buy_limit_perday":2,
            "fix":["fix0","fix1","fix2","fix3"],
            "reward":["reward0","reward1","reward2","reward3"],
            "fawn":["fawn0","fawn1","fawn2","fawn3"]
            }}

class gtestController(AppController):
    def __init__(self):
        AppController.__init__(self)
        self.setConfig(config)
        self.setCommandModule(commands)
        
class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello')
        
class AdminPage(webapp.RequestHandler):
    notice = ''
    def getNotice(self):
      temp = AdminPage.notice
      AdminPage.notice = ''
      return temp
    def setNotice(self,notice):
      AdminPage.notice = notice
      
    def get(self,cmd):
      self.handle(cmd)
    
    def post(self,cmd):
      self.handle(cmd)
        
    
    def handle(self,cmd):
      user = users.get_current_user()
      if (not user) or (not users.is_current_user_admin()) :
        self.error(401)
        self.response.out.write("401 Unauthorized")
        return
      
      logging.info("cmd:" + cmd)
      self.output = {}
      acceptCmd = ['index','importfile','exportfile',
                    'addtag','edittag','deltag',
                    'addq','editq','delq','hideq',
                    'adda','edita','dela','setright']
      if not cmd:
        cmd = "index"
        
      if cmd not in acceptCmd:
        return
      else:
        self.output['notice'] = self.getNotice()
        handler = getattr(self,cmd)
        redirect = handler()
      
        if redirect:
          self.redirect(redirect)
        else:
          path = os.path.join(os.path.dirname(__file__),'template',cmd + '.html')
          self.response.out.write(template.render(path,self.output))
      
    def index(self):
    
      tagid = int(self.request.get('tagid') or '-1')
      logging.info("index find by tag id:" + str(tagid))
      tags = DBLayer.getAllTag()
      logging.info(tags)
      if not tags.count():
        return
      
      tag = Tag.get_by_id(tagid)
      if tag:
        self.output["selecttag"] = tag
      else:
        self.output["selecttag"] = tags[0]
      self.output["tags"] = tags
        
    def importfile(self):
      file = self.request.get('upload')
      if file :
        d = tools.importFile(file)
        
      data = {"data":d }
      return 'index'
      
    def addtag(self):
      tagname = self.request.get('tagname')
      if tagname:
        tag = DBLayer.getTag(tagname)
        if tag:
          self.setNotice("you have already add this tag:" + tagname)
        else:
          tag = Tag(name=tagname)
          tag.put()
          self.setNotice("add new tag:" + tagname + " successful.")
        
      return 'index'
      
    def edittag(self):
      tagname = self.request.get('tagname')
      tagid = int(self.request.get('tagid') or '-1')
        
      if not tagname:
        self.setNotice('you didn`t input tag name')
        return 'index'
        
      if DBLayer.getTag(tagname):
        self.setNotice('this tagname:' + tagname + ' is already in use')
        return 'index'
        
      tag = Tag.get_by_id(tagid)
      if not tag:
        self.setNotice('invalid tag id')
        return 'index'
      
      tag.name = tagname
      tag.put()
      self.setNotice("edit tag successful")
      return 'index'
      
    def deltag(self):
      tagid = int(self.request.get('tagid') or '-1')
      tag = Tag.get_by_id(tagid)
      if not tag:
        self.setNotice('invalid tag id')
        return 'index'
        
      #delete question under?
      for q in tag.questions():
        q.tag = None
        q.put()
      
      tag.delete()
      self.setNotice('tag :' + str(tagid) + " is deleted.")
      
      return 'index'

class TestPage(webapp.RequestHandler):
  
  def get(self):
    from osapps.gtest import model
    tags = model.DBLayer.getAllTag()
    import os
    for a in tags:
      self.response.out.write(str(a.key().id()) + "<br>")
      
      questions = model.DBLayer.getQuestions(a)
      i = 1
      for q in questions:
        self.response.out.write("seq:"+str(q.seq)+",title:" + q.title + "<br>")
        for ans in q.answers():
          self.response.out.write(ans.text + "<br>")
          
    self.response.out.write(Tag.get_by_id(10).name)
    

application = webapp.WSGIApplication([('/',MainPage),
                                      ('/req',gtestController),
                                      ('/admin/(.*)',AdminPage),
                                      ('/test',TestPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()